package com.situ.controller;

import cn.hutool.core.util.StrUtil;
import com.situ.domain.dto.AddRoleDTO;
import com.situ.domain.dto.RolePageQueryDTO;
import com.situ.domain.dto.UpdateRoleDTO;
import com.situ.domain.entity.TRole;
import com.situ.domain.vo.BasePageQueryVO;
import com.situ.domain.vo.RoleAndMenuVO;
import com.situ.ex.ParamErrorException;
import com.situ.service.RoleService;
import com.situ.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/role")
@Tag(name = "角色接口")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;

    @GetMapping("/getRoleList")
    @Operation(summary = "获取角色列表")
    public Result<List<TRole>> getRoleList() {
        List<TRole> list = roleService.list();
        return Result.success(200, "获取角色列表成功", list);
    }

    @GetMapping("/getRolePageList")
    @Operation(summary = "获取角色分页列表")
    public Result<BasePageQueryVO<TRole>> getRolePageList(@ParameterObject RolePageQueryDTO pageQueryDTO) {
        log.info("分页查询参数：{}", pageQueryDTO);
        BasePageQueryVO<TRole> pageQueryVO = roleService.getRoleList(pageQueryDTO);
        return Result.success(200, "获取角色列表成功", pageQueryVO);
    }

    @PostMapping("/addRole")
    @Operation(summary = "添加角色接口")
    public Result addRole(@RequestBody AddRoleDTO roleDTO) {
        log.info("添加角色:{}", roleDTO);
        if (roleDTO == null
                || StrUtil.isBlankIfStr(roleDTO.getRolename())
                || StrUtil.isBlankIfStr(roleDTO.getDescription())
                || StrUtil.isBlankIfStr(roleDTO.getKeyword())) {
            throw new ParamErrorException();
        }
        roleService.addRole(roleDTO);
        return Result.ok("添加成功");
    }


    @PutMapping("/lockRole")
    @Operation(summary = "锁定或解锁角色")
    public Result lockRole(Integer status, Long id) {
        log.info("修改角色状态:{},id:{}", status, id);
        roleService.lock(status, id);
        return Result.ok("操作成功");
    }

    @GetMapping("/getRoleById")
    @Operation(summary = "根据角色id查询角色和对应的菜单信息")
    public Result<RoleAndMenuVO> getRoleAndMenuById(Long id) {
        RoleAndMenuVO roleAndMenuVO = roleService.getRoleAndMenuById(id);
        return Result.success(200, "查询成功", roleAndMenuVO);
    }

    @PutMapping("/updateRole")
    @Operation(summary = "修改角色接口")
    public Result updateRole(@RequestBody UpdateRoleDTO roleDTO) {
        log.info("修改角色:{}", roleDTO);
        if (roleDTO.getRoleid() == null ) {
            throw new ParamErrorException();
        }
        roleService.updateRole(roleDTO);
        return Result.ok("修改成功");
    }

}
